# == Schema Information
#
# Table name: invoices
#
#  id           :integer          not null, primary key
#  data_type    :integer          default("normal")
#  title        :string
#  address      :string
#  phone        :string
#  code         :string
#  bank         :string
#  bank_account :string
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#  user_id      :integer
#  is_default   :boolean          default(FALSE)
#  deleted_at   :datetime
#  content      :string
#

class Invoice < ApplicationRecord
  acts_as_paranoid without_default_scope: true

  enum data_type: [:normal, :company]

  belongs_to :user
  has_many :orders

  validates :user_id, presence: true
  validates :data_type, presence: { message: "发票类型不能为空" }
  validates :title, presence: { message: "抬头不能为空" }
  validates :address, presence: { message: "公司地址不能为空" }, if: :is_company
  validates :phone, presence: { message: "公司电话不能为空" }, if: :is_company
  validates :code, presence: { message: "纳税人识别号不能为空" }, if: :is_company
  validates :bank, presence: { message: "开户银行不能为空" }, if: :is_company
  validates :bank_account, presence: { message: "开户账号不能为空" }, if: :is_company

  after_save :set_default

  def as_json(options={})
    super({}.merge(options))
  end

  def is_company
    self.company?
  end



  def set_default
    if self.user.invoices.find_by(is_default: true).blank?
      self.is_default = true
      self.save!
    end
  end

end
